<script setup>
import {computed, ref} from "vue";
import {get} from "../../util/request.js";

const onClickLeft = () => {
  history.back()
}//导航栏返回上一个页面
const chengshi = ref([
  {
    name: '北京',
    initial: 'A'
  }
])

const name = ref("")

const initialList = ref([])

const getCityList = (name) => {
  get("city/list",{name:name}).then(res => {
    if (res.code === 0){
      initialList.value = []
      chengshi.value = res.data
      for (let i = 0; i < res.data.length; i++){
        if (!initialList.value.includes(chengshi.value[i].initial)){
          initialList.value.push(chengshi.value[i].initial)
        }
      }
    } else {
      console.log(res.data)
    }
  })
}
getCityList()

const onSearch = () => {
  getCityList(name.value)
}
const onCancel = () => {
  getCityList()
}

// 假设你想根据某个筛选条件（如首字母）来过滤chengshi数组
const filteredCities = (shouzimu) => {
  const targetInitial = shouzimu; // 这里替换为你想根据的首字母或其他筛选条件
  return chengshi.value.filter(city => city.initial.startsWith(targetInitial));
};

</script>

<template>
  <div style="width: 100vw;height: 100vh;">
    <van-nav-bar
        title="城市选择"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
        style="
        width: 100vw;
        position: relative;
        top: 0;
        left: 0;
        "
    />
    <van-search
        v-model="name"
        placeholder="请输入搜索关键词"
        show-action
        @search="onSearch"
        @cancel="onCancel"
    />
    <van-index-bar style="width: 100%;text-align: left">
      <view v-for="itemS in initialList" :key="initialList">
        <van-index-anchor :index="itemS" />
        <van-grid column-num="3" :border="false">
            <van-grid-item  v-for="item in filteredCities(itemS)" :text="item.name" @click="$router.push({path:'/index',query:{cityId:item.cityId,cityName:item.name}})"/>
        </van-grid>
      </view>
    </van-index-bar>
  </div>
</template>

<style scoped>

</style>